package com.zhu.blog.controller;



import com.zhu.blog.dao.GithubRepository;
import com.zhu.blog.dto.AccessTokenDTO;
import com.zhu.blog.dto.GitHubUserDTO;
import com.zhu.blog.model.GitHub;

import com.zhu.blog.prodriver.GithubProvider;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import java.util.Date;



@Controller
public class GitHubController {

    @Autowired
    private GithubProvider githubProvider;

    @Value("${github.client.id}")
    private String clientId;
    @Value("${github.client.secret}")
    private String clientSecret;
    @Value("${github.redirect.uri}")
    private String redirectUri;

    @Autowired
    private GithubRepository githubRepository;

    @Value("${cookie.time}")
    private Integer time;

    //回调地址
    @RequestMapping("/github/callback")
    public String callback(@RequestParam(name="code") String code,
                           @RequestParam(name="state") String state,
                           HttpServletRequest request,
                           HttpServletResponse response) throws Exception{

        AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
        accessTokenDTO.setClient_id(clientId);
        accessTokenDTO.setClient_secret(clientSecret);
        accessTokenDTO.setCode(code);
        accessTokenDTO.setRedirect_uri(redirectUri);
        accessTokenDTO.setState(state);

        if(!StringUtils.isEmpty(code) && !StringUtils.isEmpty(state)){
            HttpSession session = request.getSession();
            //解决关闭浏览器就退出登录的bug
            Cookie cookie = new Cookie("JSESSIONID", session.getId());
            cookie.setPath(request.getContextPath() + "/");
            //设置cookie过期时间为两天
            cookie.setMaxAge(time);
            response.addCookie(cookie);

            String accessToken = githubProvider.getAccessToken(accessTokenDTO);
            GitHubUserDTO user = githubProvider.getUser(accessToken);

            session.setAttribute("node_id",user.getNode_id());  //node_id用来唯一标识用户
            session.setAttribute("nickname",user.getName()); //github用户名
            session.setAttribute("avatar",user.getAvatar_url()); //github用户头像
            session.setAttribute("loginStatus","true"); //登录状态
            session.setAttribute("loginType",2); //登录方式：1 QQ，2 GitHub

            GitHub gitHubUser = githubRepository.findGitHubUser(user.getNode_id());

            if(gitHubUser == null) {
                GitHub gitHub = new GitHub();
                gitHub.setAvatar(user.getAvatar_url());
                gitHub.setGithubId(String.valueOf(user.getId()));
                gitHub.setNodeId(user.getNode_id());
                gitHub.setCreatedTime(user.getCreated_at());
                gitHub.setUpdatedTime(user.getUpdated_at());
                gitHub.setNickname(user.getName());
                gitHub.setIndexUrl(user.getHtml_url());
                gitHub.setReceivedEventsUrl(user.getReceived_events_url());
                gitHub.setPublicRepos(user.getPublic_repos());
                gitHub.setSubscriptions(user.getSubscriptions_url());
                gitHub.setLoginTime(new Date().toString());
                githubRepository.save(gitHub);
            }
            //成功就登录跳转到资料页
            return "redirect:/githubInfo";
        }
        //失败返回首页
        return "redirect:/index";
    }

    @GetMapping("/githubInfo")
    public String post(HttpSession session, Model model) throws InterruptedException{
        String node_id =(String) session.getAttribute("node_id");
        GitHub gitHubUser = githubRepository.findGitHubUser(node_id);
        session.setAttribute("avatar",gitHubUser.getAvatar());
        model.addAttribute("github",gitHubUser);
        return "githubInfo";
    }

    @PostMapping("/saveIp")
    public String post(HttpSession session,GitHub gitHub){
        String node_id =(String) session.getAttribute("node_id");
        GitHub gitHubUser = githubRepository.findGitHubUser(node_id);
        if(gitHubUser.getCip() == null){  //ip信息为空，第一次登录，将前端传来ip信息存入数据库
            githubRepository.addIpAddress(gitHub.getCip(),gitHub.getCid(),gitHub.getCname(),node_id);
        }
        return "githubInfo";
    }

    @GetMapping("/githublogout")
    public String logOut(HttpSession session){
        //退出登录，将user中的信息清除
        session.removeAttribute("loginStatus");
        session.removeAttribute("avatar");
        session.removeAttribute("nickname");
        session.removeAttribute("node_id");
        session.removeAttribute("loginType");
        return "redirect:/index";
    }
}
